package com.bq.gametrade.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;

import com.bq.gametrade.HttpLink;
import com.bq.gametrade.R;
import com.bq.gametrade.base.BaseActivity;
import com.bq.gametrade.bean.UserInfo;
import com.bq.gametrade.bean.UserInfoDetails;
import com.bq.gametrade.http.VRHttp;
import com.bq.gametrade.http.VRHttpListener;
import com.bq.gametrade.jpush.ExampleUtil;
import com.bq.gametrade.utils.SharedPreferencesUtils;
import com.bq.gametrade.utils.SystemUtils;

import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;

public class WelcomeActivity extends BaseActivity {

    private int count = 4;
    private Animation animation;
    private Button btnTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_welcome);

        JPushInterface.init(WelcomeActivity.this);
        registerMessageReceiver();
        initView();
        animation = new AlphaAnimation(0.1f, 1f);
        handler.sendEmptyMessageDelayed(0, 1000);
        getAccount();

    }

    private void getAccount(){
        String userName = (String)SharedPreferencesUtils.getValue(WelcomeActivity.this,SharedPreferencesUtils.user_account,"");
        String userPassword = (String)SharedPreferencesUtils.getValue(WelcomeActivity.this,SharedPreferencesUtils.user_passwor,"");
        if(!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(userPassword)){
            userToLogin(userName,userPassword);
        }else {
        }
    }

    private void initView() {
        Log.e("wu",JPushInterface.getRegistrationID(WelcomeActivity.this));
        btnTime = (Button) findViewById(R.id.btn_time);
        btnTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
                startActivity(intent);
                handler.removeMessages(0);
                finish();
            }
        });
    }

    private void userToLogin(String userName,String password) {
        /**
         * loginType=wx  微信登录
         *loginType=ali 支付宝 （预留）
         *loginType=0   普通登录
         */
        Map<String, String> params = new HashMap<>();
        params.put("username", userName);
        params.put("password", password);
        params.put("loginType", "0");
        params.put("deviceType", "1");
        params.put("deviceId", JPushInterface.getRegistrationID(WelcomeActivity.this));
        VRHttp.userToLogin(WelcomeActivity.this, HttpLink.LOGIN_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                closeSpotsDialog();
                UserInfo userInfo = (UserInfo)response;
                if(userInfo.status.equals("0")){
                    UserInfoDetails userInfoDetails = userInfo.userinfo;
                    application.setUserInfo(userInfoDetails);
                }else{
                    toastShow("登录超时请重新登陆");
                    application.setUserInfo(null);
                }
            }

            @Override
            public void onError(String error) {
                super.onError(error);

            }
        });
    }



    private int getCount() {
        count--;
        if (count == 1) {
            boolean isFirstLogin = (boolean)SharedPreferencesUtils.getValue(WelcomeActivity.this,SharedPreferencesUtils.first_login,false);
            if(isFirstLogin){
                startActivity( new Intent(WelcomeActivity.this, MainActivity.class));
            }else {
                startActivity( new Intent(WelcomeActivity.this, GuideActivity.class));
            }

            finish();
        }
        return count;
    }

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) {
                btnTime.setText(getCount() + "S");
                handler.sendEmptyMessageDelayed(0, 1000);
                animation.reset();
                btnTime.startAnimation(animation);
            }

        }

        ;

    };


    public static boolean isForeground = false;
    @Override
    protected void onResume() {
        isForeground = true;
        JPushInterface.onResume(WelcomeActivity.this);
        super.onResume();
    }

    @Override
    protected void onPause() {
        isForeground = false;
        JPushInterface.onPause(WelcomeActivity.this);
        super.onPause();
    }


    @Override
    protected void onDestroy() {
        unregisterReceiver(mMessageReceiver);
        super.onDestroy();
    }




    //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                String messge = intent.getStringExtra(KEY_MESSAGE);
                String extras = intent.getStringExtra(KEY_EXTRAS);
                StringBuilder showMsg = new StringBuilder();
                showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                if (!ExampleUtil.isEmpty(extras)) {
                    showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                }
            }
        }
    }


}
